package master;


import java.util.List;

/**
 *
 * 两两交换链表中的节点
 *
 * @author chenyw
 * @date 2022/7/24 10:58
 */
public class M24swapPairs {
/*    //迭代
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = head;
        head = head.next;
        pre.next = head.next;
        head.next = pre;
        ListNode p = pre.next;
        while (p != null && p.next != null) {
            //交换
            ListNode tmp = p;
            p = p.next;
            tmp.next = p.next;
            p.next = tmp;

            //连接
            pre.next = p;
            p = tmp.next;
            pre = tmp;

        }
        return head;
    }*/

    //递归
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        head.next = swapPairs(newHead.next);
        newHead.next = head;
        return newHead;
    }
}
